package com.py.credit.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.util.Map;

public class FreeeMarkerUtils {

    private static final String FONT = "template/simhei.ttf";
    private static Configuration freemarkerCfg = null;

    static {
        freemarkerCfg = new Configuration();
        //freemarker的模板目录
        try {
            freemarkerCfg.setDirectoryForTemplateLoading(new File(PathUtil.getCurrentPath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据 Freemarker模板引擎生成PDF文件
     *
     * @param data         模板中用到的数据对象
     * @param templatePath 模板地址
     * @param destPath     生成的文件地址
     * @return
     */
    public static boolean html2Pdf(Map<String, Object> data, String templatePath, String destPath, String fileName, String absolutepath) {
        boolean flag = true;
        try {
            File file = new File(destPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String content = FreeeMarkerUtils.freeMarkerRender(data, templatePath);
            String waterPath = null != data.get("waterPath") ? String.valueOf(data.get("waterPath")) : "";
            FreeeMarkerUtils.createPdf(content, destPath, fileName, absolutepath, waterPath);
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
        } catch (DocumentException e) {
            flag = false;
            e.printStackTrace();
        } catch (com.lowagie.text.DocumentException e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    /**
     * freemarker渲染html
     */
    public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();
        try {
            // 获取模板,并设置编码方式
            Template template = freemarkerCfg.getTemplate(htmlTmp, "UTF-8");
            template.setEncoding("UTF-8");
            // 合并数据模型与模板
            template.process(data, out); //将合并后的数据和模板写入到流中，这里使用的字符流
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    public static void createPdf(String content, String dest, String fileName, String absolutepath, String waterPath) throws IOException, DocumentException, com.lowagie.text.DocumentException {
        ITextRenderer render = new ITextRenderer();
        ITextFontResolver fontResolver = render.getFontResolver();
        fontResolver.addFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 解析html生成pdf
        render.setDocumentFromString(content);
        //解决图片相对路径的问题
        if (StringUtils.isNotBlank(waterPath)) {
            render.getSharedContext().setBaseURL("file://" + absolutepath + waterPath);
        } else {
            render.getSharedContext().setBaseURL("file://" + absolutepath);
        }

        render.layout();
        render.createPDF(new FileOutputStream(dest + File.separator + fileName));
    }
}
